﻿using System;
using System.Collections.Generic;
using System.Linq;
using CodeGenerator.interfaces;

namespace CodeGenerator.Implementations
{
    class DataBaseTable : IDataBaseTable
    {
        private IDatabaseProvider _databaseProvider { get; set; }
        private string _tableName = "";
        private IList<IDatabaseColumn> _columns = new List<IDatabaseColumn>();
        private IList<IDatabaseColumn> _primaryKey = new List<IDatabaseColumn>();
        private IList<IUniqueConstraint> _uniqueIndexes = new List<IUniqueConstraint>();
        private IList<IForeignKey> _foreignKeys = new List<IForeignKey>();
        private IGeneratorModel _model;
        public DataBaseTable(IGeneratorModel Model, string Name, IDatabaseProvider DatabaseProvider)
        {
            _model = Model;
            _databaseProvider = DatabaseProvider;
            _tableName = Name;
            
            LoadColumns();
            LoadForeignKeys();
            LoadPrimaryKey();
            LoadUniqueIndexes();
        }

        private void LoadUniqueIndexes()
        {
            _uniqueIndexes = (IList<IUniqueConstraint>) _databaseProvider.GetUniqueIndexes(_tableName);
        }

        private void LoadForeignKeys()
        {
            _foreignKeys = _databaseProvider.GetTableForeignKeys(_tableName, _model) ;
        }

        private void LoadColumns()
        {
            _columns = _databaseProvider.GetTableColumns(_tableName);
        }

        private void LoadPrimaryKey()
        {
            _primaryKey = _databaseProvider.GetTablePrimaryKeyColumns(_tableName);
        }

        public string TableName
        {
            get { return _tableName; }
            set { _tableName = value; }
        }

        public IList<IDatabaseColumn> Columns
        {
            get { return _columns; }
        }

        public IList<IDatabaseColumn> PrimaryKey
        {
            get { return _primaryKey; }
        }

        public IList<IForeignKey> ForeignKeys
        {
            get { return _foreignKeys; }
        }

        IList<IUniqueConstraint> IDataBaseTable.UniqueIndexes
        {
            get { return _uniqueIndexes; }
        }

        public bool HaveIdentityColumn
        {
            get { return (from IDatabaseColumn n in _columns where n.IsIdentity select n).Count() > 0; }
        }
    }
}